<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Apartment locations on Google maps</title>

<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAA1mzqS7NiKb1OAAZb1mZeChR-1q5lCaUZqUlJlfaPceTU435QxhRdGlOzvjs0_EQidjO0ekFSl8MvhQ&sensor=true"
        type="text/javascript"></script>

<script type="text/javascript">
  var parser = new DOMParser();
  var geocoder = null;
  var map = null;
  
  var selectedId = null;
  var selectedAddress = null; 
  var length = null;

  function getFirstFoundAddress(xmldom) {
    var firstFoundAddress = null;

    if (!xmldom) {
      return firstFoundAddress;
    }

    var alinksArray = xmldom.getElementsByTagName("a");
    if (alinksArray) {
      var arrayLength = alinksArray.length;
      for (var i = 0; i < arrayLength; i++ ) {
        var href = alinksArray.item(i).getAttribute("href");
        var re = /^http:\/\/maps\.google\.com\/\?q=loc(%3A)?/;
        if (href && href.match(re)) {
          firstFoundAddress = href.replace(re, "");
          firstFoundAddress = firstFoundAddress.replace(/\+/g, " ");
          firstFoundAddress = firstFoundAddress.replace(/%[\d\w]+/g, "");
          break;
        } // if
      } // for (var i=0; ...)
    } // if(alinksArray)

    return firstFoundAddress;
  } // getFirstFoundAddress

  function adjustMap(marker) {
     var firstBounds = map.getBounds();
     if (!firstBounds.containsLatLng(marker.getLatLng())) {
        firstBounds.extend(marker.getLatLng());
        var zoomLevel = map.getBoundsZoomLevel(firstBounds);
        map.setCenter(firstBounds.getCenter(), zoomLevel);
     }
  };

  function createMaps() {

     selectedId = chrome.extension.getBackgroundPage().selectedId;
     selectedAddress = chrome.extension.getBackgroundPage().addresses[selectedId];
     length = selectedAddress.length;

    if (geocoder) {
       map.clearOverlays();
       map.setCenter(new GLatLng(37.4419, -122.1419), 13);
       plotSingleAddressPoint(0, length);
    } // if (geocoder)
   
    function plotSingleAddressPoint(index, length) {
      if (index < 0 || index >= length) {
         return;
      }
      
      var link = selectedAddress.mapPoints[index].link;
      var title = selectedAddress.mapPoints[index].title;

      if (selectedAddress.mapPoints[index].parsed == null) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", link, true);
        xhr.onload = xhrOnLoaded;
        xhr.send(null);

        function xhrOnLoaded() {
          var re = /<small(.|\n)+small>/;
          var matched = xhr.responseText.match(re);
          var xmldom = null;

          if (matched) {
            xmldom = parser.parseFromString(matched[0], "text/xml");
          }

		  selectedAddress.mapPoints[index].parsed = true;
          var address = getFirstFoundAddress(xmldom);
          if (address != null) {
            selectedAddress.mapPoints[index].mapLocation = address;
            var tooltip = [[index+1, ":", title].join(" "),
                            link,
                            address
                           ].join("\n");
            geocoder.getLatLng(address, getCustomSetMarkerFunction(tooltip, link, index, length));
          } else {
            plotSingleAddressPoint(index+1, length);
          }// if (address != null)
		  
        } // xhrOnLoaded
      } else { 
            address = selectedAddress.mapPoints[index].mapLocation;
            var tooltip = [[index+1, ":", title].join(" "),
                            link,
                            address
                           ].join("\n");
            var gPoint = selectedAddress.mapPoints[index].gPoint;
            if (gPoint == null) {
            	plotSingleAddressPoint(index+1, length);
            } else {
            	(getCustomSetMarkerFunction(tooltip, link, index, length))(gPoint);
            }
      
      }// if (selectedAddress...)
    } // plotSingleAddressPoint
    
  function getCustomSetMarkerFunction(tooltip, address, index, length) {
    var markerFunc = function(point) {
                        if (point) {
                          var marker = new GMarker(point, {title: tooltip});
                          map.addOverlay(marker);
                          GEvent.addListener(marker, "dblclick", function() {
								    chrome.tabs.create({url: address, active:false});
                                                                 }
                                             );                                
                          adjustMap(marker);
                          selectedAddress.mapPoints[index].gPoint = point;
                        } // if (point)
                        plotSingleAddressPoint(index + 1, length);
                      };
    return markerFunc;
  } // getCustomSetMarkerFunction
    
  } // createMaps

  function initialize() {
    if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.enableDoubleClickZoom();
      map.enableContinuousZoom();
      map.enableScrollWheelZoom();
      map.enablePinchToZoom();
      
      geocoder = new GClientGeocoder();
      createMaps();
    }
  } // initialize
 
</script>
	<script type="text/javascript">
	
	  var _gaq = _gaq || [];
	  //_gaq.push(['_setAccount', 'UA-20630894-1']);
	  _gaq.push(['_trackPageview']);
	
	  (function() {
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	  })();
	
	</script>
</head>

<body onload="initialize()">
  <!--
  <button onclick="createMaps()">
    Plot Addresses on the map
  </button>
  <br/>
   -->
  <br/>

  <div id="map" style="width: 500px; height: 500px" ></div>
</body>
</html>
